package com.epoint.netty.helloworld;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.apache.commons.lang3.StringUtils;

public class NettyClient {

    private final String host;
    private final int port;

    public NettyClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void start() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new HexClientHandler());
                        }
                    });

            // 连接到服务器
            ChannelFuture future = bootstrap.connect(host, port).sync();
            System.out.println("Connected to server at " + host + ":" + port);

            // 等待连接关闭
            future.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        String host = "10.211.12.154"; // 服务器地址
        int port = 28899; // 服务器端口

        new NettyClient(host, port).start();
    }
}

class HexClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        // 将 ByteBuf 转换为字节数组
        byte[] bytes = new byte[msg.readableBytes()];
        msg.readBytes(bytes);


        String result = new String(bytes);
        String[] resultArray = result.split(" ");
        if (resultArray.length >= 3) {
            result = "";

            int weight;
            for (weight = 1; weight < resultArray.length; ++weight) {
                if (hasText(resultArray[weight])) {
                    result = resultArray[weight];
                    break;
                }
            }

            weight = 0;
            if (!result.isEmpty()) {
                weight = Integer.parseInt(result);
            }
            System.out.println("Parsed data: " + weight);
        }
//        // 1. 打印原始 HEX 数据
//        String hexString = bytesToHex(bytes);
//
//        System.out.println("Received HEX data: " + hexString);
//        // 2. 解析 HEX 数据为可阅读的格式
//        String readableData = parseHexData(bytes);
//        System.out.println("Parsed data: " + readableData);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    // 将字节数组转换为 HEX 字符串的工具方法
    private static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }

    // 解析 HEX 数据为可阅读的格式
    private static String parseHexData(byte[] bytes) {
        // 示例：假设 HEX 数据是 ASCII 编码的字符串
        return new String(bytes, java.nio.charset.StandardCharsets.US_ASCII);
    }

    private boolean hasText(CharSequence str) {
        if (!hasLength(str)) {
            return false;
        } else {
            int strLen = str.length();

            for(int i = 0; i < strLen; ++i) {
                if (!Character.isWhitespace(str.charAt(i))) {
                    return true;
                }
            }

            return false;
        }
    }
    private boolean hasLength(CharSequence str) {
        return str != null && str.length() > 0;
    }

}